package com.jaya.budan.receiver;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.jaya.budan.R;
import com.jaya.budan.activity.LoginActivity;
import com.jaya.budan.activity.MainActivity;
import com.jaya.budan.bean.VIP_JiLu;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.Utils;
import com.jaya.budan.utils.VolleyUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

public class MyBroadCastReceiver extends BroadcastReceiver{

    private final String HOME_DIALOG_REASON = "homereason";
    private final String HOME_DIALOG_REASON_HOME = "homekey";
    private Context mcontext;
    @Override
    public void onReceive(Context context, Intent intent) {
        if ("com.jaya.budan".equals(intent.getAction())) {
            Log.d("BroadcastReceiver", "onReceive");
        }
        if (intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            String reason = intent.getStringExtra(HOME_DIALOG_REASON);
            if (reason != null && reason.equals(HOME_DIALOG_REASON_HOME)) {
                ToolUtils.showToast(context, "点击Home键");
                return;
            }
        }
        mcontext = context;
        Bundle bundle = intent.getExtras();
        Log.d("MyBroad", "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle, context));
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d("MyBroad", "[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            String data = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            Log.d("MyBroad", "[MyReceiver] 接收到推送下来的自定义消息: " + data);
            //在此操作
            processCustomMessage(context, data, bundle);
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d("MyBroad", "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.d("MyBroad", "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d("MyBroad", "[MyReceiver] 用户点击打开了通知");
            //打开自定义的Activity
            Intent i = new Intent(context, MainActivity.class);
//            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.putExtra("access_token", "");//空值
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(i);
            //点击一个通知之后取消掉所有notification
            NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            nm.cancelAll();
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d("MyBroad", "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.d("MyBroad", "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            Log.d("MyBroad", "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    @SuppressLint("SetTextI18n")
    private void processCustomMessage(Context context, String str, Bundle bundle){
        ToolUtils.showToast(context, "" + str);
        try {
            JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
            Log.d("MyBroad", "*****" + json.toString());
            Gson gson = new Gson();
            VIP_JiLu vip_jiLu = gson.fromJson(json.toString(), VIP_JiLu.class);
            Log.d("MyBroad", "*****" + vip_jiLu.getIs_online());
            if (vip_jiLu.getIs_online() == 1){//用户退出登录，单点登录
                Dialog dialo = new Dialog(context, R.style.Dialog);
                dialo.setCanceledOnTouchOutside(false);//设置外部不可点击
                dialo.setCancelable(false);
                dialo.setContentView(R.layout.pop_my_wallet_bind_bankcard_tishi);
                dialo.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                TextView tv_my_wallet_tishi = dialo.findViewById(R.id.tv_my_wallet_tishi);
                TextView img_guanbi = dialo.findViewById(R.id.img_guanbi);
                tv_my_wallet_tishi.setText("该账号已于" + vip_jiLu.getLogin_time() + "在其他设备上登录，您已被强制下线。如非本人操作请及时修改登录密码。");
                img_guanbi.setText("确定");
                img_guanbi.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialo.dismiss();
                        postData(context, vip_jiLu.getToken());
                    }
                });
                if (Utils.getAppOps(mcontext)){
                    dialo.show();
                } else {
                    dialo.cancel();
                }
            }
        } catch (JSONException e) {
            Log.d("MyBroad", "Get message extra JSON error!");
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle, final Context context) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    Log.d("MyBroad", "This message has no Extra data");
                    continue;
                }
                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Log.d("MyBroad", "" + json.toString());
                    Iterator<String> it = json.keys();
                    Log.d("MyBroad", "" + it.toString());
                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" + myKey + " - " + json.optString(myKey) + "]");
                        Log.d("MyBroad", "" + json.optString(myKey));
                    }
                } catch (JSONException e) {
                    Log.d("MyBroad", "Get message extra JSON error!");
                }
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
            if (key.equals("cn.jpush.android.ALERT")) {
                Log.d("MyBroad", "1" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    /**
     * 判断程序是否打开 * @returnn
     */
    public static boolean isRunningInForeground(Context context) {
        boolean isActivityFound = false;
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> services = activityManager.getRunningTasks(1);
        if (services.get(0).topActivity.getPackageName().toString().equalsIgnoreCase(context.getPackageName().toString())) {
            isActivityFound = true;
        }
        return isActivityFound;
    }

    private static final int REQUEST_CODE = 1;

    //判断权限
    private boolean isCanDrawOverlays(Context context) {
        Boolean result = true;
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                Class clazz = Settings.class;
                Method canDrawOverlays = clazz.getDeclaredMethod("canDrawOverlays", Context.class);
                result = (Boolean) canDrawOverlays.invoke(null, context);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    //申请权限
    private void requestAlertWindowPermission(Context context) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
//        startActivityForResult(intent, REQUEST_CODE);
    }

    /**
     * 网络请求
     */
    private void postData(Context context, String token) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.out_login_Url + token, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("register", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Utils.logOut(context);
//                        System.exit(0);
                        Intent intent = new Intent(context, LoginActivity.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent);
                    } else {
                        ToolUtils.showToast(context, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(context, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(context).add(request);
    }
}
